package o2o.web.actions.agent;


import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.*;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.shop.ShopMemory;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.VO.agent.CityAgentSchoolVO;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.shop.ShopInfoVO;
import org.apache.commons.lang3.StringUtils;
import o2o.system.data.SYS_SETTINGS;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CityAgentMan {


    //根据经纬度获取最近的代理
    public static CityAgentVO getCityAgent(String city, Double lat, Double lng) {
        List<CityAgentVO> list = getCityAgentList(city, lat, lng);
        if (ValidateUtil.isAbsList(list)) {
            return list.get(0);
        }
        return null;
    }

    //根据经纬度获取最近的商圈
    public static List<CityAgentVO> getCityAgentList(String city, Double lat, Double lng) {
        if (ValidateUtil.isNotLatLng(lat, lng)) {//按距离排序
            return null;
        }
        List<CityAgent> list = null;

        if (null != SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG && 0 == 1 - SYS_SETTINGS.SHOP_LIST_GET_BY_LAT_LNG) {
            list = CityAgentMemory.getInstance().list();
        } else {
            list = CityAgentMemory.getInstance().listOfCity(city);
        }
        if (ValidateUtil.isAbsList(list)) {
            List<CityAgentVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityAgent cityAgent = list.get(i);
                if (null == cityAgent) {
                    continue;
                }

                CityAgentVO vo = new CityAgentVO();
                try {
                    ObjectUtils.copyPropertiesExclude(cityAgent, vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                Double distinct = Geohash.distance(lat, lng, vo.getLat(), vo.getLng());
                Integer agentRange = vo.getRang();
                if (ValidateUtil.isNotAbsInteger(agentRange)) {
                    agentRange = 0;
                }

                // 是否启用电子围栏 0.不使用电子围栏 1.使用电子围栏
                if (null != SYS_SETTINGS.IS_ELECTRONIC_FENCE && 0 == 1 - SYS_SETTINGS.IS_ELECTRONIC_FENCE) {
                    // 判断该用户是否在商圈内(多边形)
                    if (StringUtils.isEmpty(vo.getLnglats())) {
                        continue;
                    }
                    String[] latlngs = vo.getLnglats().split(";");
                    Double[] lngArr = new Double[latlngs.length];
                    Double[] latArr = new Double[latlngs.length];
                    for (int j = 0; j < latlngs.length; j++) {
                        String[] lnla = latlngs[j].split(",");
                        lngArr[j] = Double.parseDouble(lnla[0]);
                        latArr[j] = Double.parseDouble(lnla[1]);
                    }

                    Boolean flag = Geohash.isInPolygon(lng, lat, lngArr, latArr);
                    if (!flag) {
                        continue;
                    }
                } else {
                    Double range = JYMathDoubleUtils.mul(agentRange, 1000);
                    if (range <= 0) {
                        range = 500d;
                    }
                    if (range - distinct <= 0) {
                        continue;
                    }
                }
                vo.setDistinct(distinct);
                voList.add(vo);
            }
            Collections.sort(voList, new Comparator<CityAgentVO>() {
                public int compare(CityAgentVO arg0, CityAgentVO arg1) {
                    return arg0.getDistinct().compareTo(arg1.getDistinct());//倒叙排列
                }
            });
            if (ValidateUtil.isAbsList(voList)) {
                return voList;
            }
        }

        return null;
    }

    //获取代理信息
    public static CityAgentSchoolVO getCityAgentDetailInfoById(Long agentId) {
        return getCityAgentDetailInfoById(agentId, true, true, true);
    }

    public static CityAgentSchoolVO getCityAgentDetailInfoById(Long agentId, Boolean hasShopInfo, Boolean hasRecommendGoods, Boolean hasAdvert) {
        if (ValidateUtil.isNotID(agentId)) {
            return null;
        }
        CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
        if (null == cityAgent) {
            return null;
        }
        CityAgentSchoolVO cityAgentSchoolVO = new CityAgentSchoolVO();
        try {
            ObjectUtils.copyPropertiesExclude(cityAgent, cityAgentSchoolVO, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (hasShopInfo) {//如果有店铺信息
            ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(cityAgent.getUsername());
            if (null == shopInfo) {
                return null;
            }

            ShopInfoVO shopInfoVO = new ShopInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            cityAgentSchoolVO.setShopInfo(shopInfoVO);

        }
        return cityAgentSchoolVO;
    }

    // 添加设置
    public static ResultInfo copyPlateSettingForAgent(Long agentId, String username) {
        OrderOverTimeInfo info = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
        if (info == null) {
            info = getOrCreatePlateDefaultOrderOverInfo();
            if (info == null) {
                return new ResultInfo("平台未设置订单超时提醒");
            }
        }
        long cTime = DateUtils.getCurrTime();
        info.setAgentId(agentId).setId(null).setCreateUser(username).setDelFlag(0).setUpdateUser(null).setCreateTime(cTime).setUpdateTime(null);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.AGENT_ORDER_OVERTIME, info);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo("新建失败，请稍后重试");
        }
        // 缓存
        AgentOrderOverTimeMemory.getInstance().add(cTime);
        return new ResultInfo();
    }

    // todo  创建或者获取一个默认的平台配置信息
    public static synchronized OrderOverTimeInfo getOrCreatePlateDefaultOrderOverInfo() {
        OrderOverTimeInfo info = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
        if (info != null) {
            return info;
        }
        Long cTime = DateUtils.getCurrTime();
        // 创建一个
        // insert into `agent_order_overtime` (`id`, `sysAppKey`, `agentId`, `orderOverTime`, `alertOrderTime`, `shopNotSureTime`, `shopOverTime`, `shopReadyTime`, `alertShopReadyTime`, `alertShopTime`, `postmanOverTime`, `postmanAdvanceTime`, `notTakenOrderTime`, `alertPostmanTime`, `postmanBackOrderTime`, `appointPostmanTime`, `appointShopTime`, `appointShopAlertTime`, `postmanCanChangeCountPreDay`, `postmanMaxOrderNum`, `postmanCanGrabOrder`, `isOpen`, `delFlag`, `createUser`, `createTime`, `updateUser`, `updateTime`) values('1',NULL,'-1','40','5','0','30','0','0','5','30','0','0','5','0','60','-1','60','-1','-1','-1','1','0',NULL,'0',NULL,'2019-03-25 18:37:28');
        info = new OrderOverTimeInfo();
        info.setDelFlag(0).setCreateTime(cTime).setCreateUser("admin");
        info.setAgentId(-1L).setOrderOverTime(40).setAlertOrderTime(5).setOutOneKmTime(0).setWithPsKmInRang(0.0).setFixedOrderPsTime(0)
                .setShopNotSureTime(0).setShopOverTime(30)
                .setShopReadyTime(0).setAlertShopReadyTime(0)
                .setPostmanOverTime(30).setPostmanAdvanceTime(0)
                .setNotTakenOrderTime(0).setAlertPostmanTime(0)
                .setPostmanBackOrderTime(0).setAppointPostmanTime(60)
                .setAppointShopTime(-1).setAppointShopAlertTime(60)
                .setPostmanCanChangeCountPreDay(-1).setPostmanCanGrabOrder(-1)
                .setIsOpen(1);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.AGENT_ORDER_OVERTIME, info);
        } catch (Exception e) {
            e.printStackTrace();

        }
        // 缓存
        AgentOrderOverTimeMemory.getInstance().add(cTime);
        return AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
    }

}
